package com.luculent.action;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import java.util.Set;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebElement;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.ImmutableMap;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.luculent.base.FPBDriverProxy;
import com.luculent.base.RCode;
import com.luculent.result.Response;
import com.luculent.utils.FPBTableUtils;
import com.luculent.utils.WorkId;

import cn.hutool.crypto.digest.HMac;
import cn.hutool.crypto.digest.HmacAlgorithm;
import lombok.extern.slf4j.Slf4j;  

@Controller 
@RequestMapping("/cf_fpb/api/fupin")
@Slf4j
public class FPBNewController extends FPBDriverProxy{
	
    @RequestMapping(params ="iw-cmd=workId") 
    @ResponseBody
    public String workId(HttpServletResponse response,HttpServletRequest request,HttpSession session,
    		@RequestParam(value="ym",required = true) String ym,
    		@RequestParam(value="requestId",required = true) String requestId) throws Exception{
    	 
    	String r = request.getHeader("x")+"="+requestId+"="+ym+"="+WorkId.sortUID();
    	long sl = new Random().nextInt(2000);
    	Thread.sleep(sl);
    	if(Integer.valueOf(ym) == 2){
    		Thread.sleep(1000);
    		throw new RuntimeException();
    	}
    	if(Integer.valueOf(ym) == 5){
    		return "";
    	}
    	log.debug(r);
    	//String a =requestId+ "{\"options\":{\"opt\":\"query\",\"type\":\"dao\",\"code\":1,\"errorMsg\":null,\"baz002\":null},\"body\":{\"poorFamilyList\":{\"sqlId\":\"queryGrid\",\"data\":[{\"aac001\":3000470031,\"aar040\":2019,\"aad001\":150402001001,\"aar012\":\"15019640645\",\"aaq002\":\"中国邮政储蓄银行\",\"aac004\":\"601951001200747550\",\"aac005\":\"01\",\"aac006\":\"05\",\"aac007\":\"01\",\"aac008\":\",\",\"aac011\":null,\"aac012\":\"0\",\"aac013\":null,\"aac014\":null,\"aac017\":5,\"aac019\":null,\"aar010\":1,\"aad041\":null,\"aar100\":\"1\",\"aar057\":null,\"aar058\":null,\"aac025\":300001675742,\"aac029\":\"张雪\",\"aac031\":\"150402196007162016\",\"aar022\":null,\"aar001\":\"150402000000\",\"aar023\":\"150402000\",\"aar024\":20191230105001,\"aar025\":\"红山区\",\"baz002\":4301101133312475,\"aar008\":\"150402001001\",\"aar007\":\"15040200100101\",\"aac015\":null,\"aac023\":\"2015年底\",\"aac024\":null,\"aac028\":null,\"aac027\":null,\"aar041\":2014,\"acr077\":null,\"show\":\"0\",\"aac009\":null,\"aac042\":null,\"aac090\":null,\"aac041\":null,\"aac032\":null,\"aac033\":null,\"aac034\":null,\"aac035\":null,\"aac036\":null,\"aar108\":null,\"aar109\":null,\"aar110\":null},{\"aac001\":3000470034,\"aar040\":2019,\"aad001\":150402001001,\"aar012\":\"04768900082\",\"aaq002\":\"中国邮政储蓄银行\",\"aac004\":\"601951001200747816\",\"aac005\":\"01\",\"aac006\":\"05\",\"aac007\":\"09\",\"aac008\":\",\",\"aac011\":null,\"aac012\":\"0\",\"aac013\":null,\"aac014\":null,\"aac017\":3,\"aac019\":null,\"aar010\":4,\"aad041\":null,\"aar100\":\"1\",\"aar057\":null,\"aar058\":null,\"aac025\":300001675062,\"aac029\":\"卢银\",\"aac031\":\"150402196601052012\",\"aar022\":null,\"aar001\":\"150402001000\",\"aar023\":\"150402001\",\"aar024\":20191122113144,\"aar025\":\"红庙子镇\",\"baz002\":4301101127706269,\"aar008\":\"150402001001\",\"aar007\":\"15040200100101\",\"aac015\":null,\"aac023\":\"2015年底\",\"aac024\":null,\"aac028\":null,\"aac027\":null,\"aar041\":2014,\"acr077\":null,\"show\":\"0\",\"aac009\":null,\"aac042\":null,\"aac090\":null,\"aac041\":\"2015年底\",\"aac032\":null,\"aac033\":null,\"aac034\":null,\"aac035\":null,\"aac036\":null,\"aar108\":null,\"aar109\":null,\"aar110\":null}],\"namespace\":\"com.neusoft.biz.core.mapping.Ac01Mapper\",\"page\":{\"startRow\":0,\"pageSize\":2,\"total\":-1},\"conditions\":{\"AAR002\":\"150000000000\",\"condition_diy\":[],\"AAR003\":\"150400000000\",\"AAR004\":\"150402000000\",\"AAR005\":\"\",\"show\":0,\"aar040\":2019,\"aar010\":[],\"query_AAR040\":\"2019\",\"aar008\":\"150402\",\"aac005\":\"\",\"aab004\":\"\",\"aac006\":[],\"aab002\":\"\"}},\"numberForm\":{\"sqlId\":\"queryNumber\",\"data\":[{\"RNUM\":1501,\"HNUM\":620}],\"namespace\":\"com.neusoft.biz.core.mapping.Ac01Mapper\",\"page\":{\"startRow\":-1,\"pageSize\":0,\"total\":1},\"conditions\":{\"AAR002\":\"150000000000\",\"condition_diy\":[],\"AAR003\":\"150400000000\",\"AAR004\":\"150402000000\",\"AAR005\":\"\",\"show\":0,\"aar040\":2019,\"aar010\":[],\"query_AAR040\":\"2019\",\"aar008\":\"150402\",\"aac005\":\"\",\"aab004\":\"\",\"aac006\":[],\"aab002\":\"\"}}}}";

    	return r;
    } 
    
    
    
    @RequestMapping(params ="iw-cmd=vcode") 
    public void code1(HttpServletResponse response,HttpServletRequest request) throws UnsupportedOperationException, IOException{
    	//退出登录
    	super.loginFlag = false;
    	driver.get("http://106.38.235.201:7080/portal/techcomp/idm/logout.jsp"); 
    	//driver.get("http://106.38.235.201:7080/cas/login"); 
        //设置等待时间,防止页面没有渲染完成导致抓取元素失败  
        //寻找验证码容器
    	WebElement ele = null;
    	try {
    		ele = driver.findElement(By.id("jcaptcha"));
		} catch (Exception e) {
			//1、网站异常没有找到jcaptcha元素。
			//2、已经等了成功,要退出重新登
			try {
				if(e instanceof NoSuchElementException){
					driver.findElement(By.xpath("//*[@id=\"pheaderCont\"]/a")).click();
					ele = driver.findElement(By.id("jcaptcha"));
				}	
			} catch (Exception e2) {
				if(e2 instanceof NoSuchElementException){
					 //网站异常
				}
			}
			
		}
    	 
        //创建一个快照
        File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        //读取截图
        BufferedImage fullImg = ImageIO.read(screenshot);
        //获取页面上元素的位置
        org.openqa.selenium.Point point= ele.getLocation();
        //获取元素宽高  
        int eleWidth= ele.getSize().getWidth();  
        int eleHeight= ele.getSize().getHeight();
        //裁剪整个页面截图只得到元素截图  
        BufferedImage buffImg= fullImg.getSubimage(point.getX(), point.getY(), eleWidth, eleHeight);  
        
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Content-Type","image/jpeg;charset=UTF-8");//设置响应的媒体类型，这样浏览器会识别出响应的是图片
		ServletOutputStream sos = response.getOutputStream();
        ImageIO.write(buffImg, "png", sos);
        sos.close();
    } 
    
    @RequestMapping(params ="iw-cmd=login") 
    @ResponseBody
    public String login1(@RequestParam(value="username",required = true) String username,
    		@RequestParam(value="Password",required = true) String password,
    		@RequestParam(value="yzm",required = true) String code){
         
        driver.findElement(By.id("username")).clear(); 
        driver.findElement(By.id("username")).sendKeys(username);
        driver.findElement(By.id("password")).clear(); 
        driver.findElement(By.id("password")).sendKeys(password);
        //寻找验证码编辑框
        driver.findElement(By.id("jcaptcha_response")).clear();
        driver.findElement(By.id("jcaptcha_response")).sendKeys(code); 
        //模拟点击登录按钮
        driver.findElement(By.id("loginBut")).click();
        String currentHandle = driver.getWindowHandle();
        Set<String> handles = driver.getWindowHandles();  
        try {
        	handles.forEach( h -> { 
        		if (h != currentHandle) { 
        			driver.switchTo().window(h); 
        			driver.findElement(By.className("menuIcon1")).click();  
        			int t = new Random().nextInt(3) + 1;
                 	driver.findElement(By.xpath("//*[@id='dialog']/div/center/div/div/ul/li["+t+"]/a")).click();   
                }
        	}); 
		} catch (Exception e) { 
			if(e instanceof NoSuchElementException){ 
				return login2(username,password);
			}
			e.printStackTrace();  
			return Response.fail(); 
		} 
        return factch(); 
    } 
   
    @RequestMapping(params ="iw-cmd=pinkunhuxinxiliebiao") 
    @ResponseBody
    public Object pkh(HttpSession session,@RequestParam(value="YM",required = false) String ym,
    		@RequestParam(value="ND",required = true) String nd,
    		@RequestParam(value="SZXIAN",required = true) String xian){
    	if(!super.loginFlag){ 
	    	return Response.noLogin();
		} 
    	int pageSize = 30;
    	int startRow = 30 * (Integer.valueOf(StringUtils.isBlank(ym)?"1":ym) - 1);
    	String condtion = "{\"options\":{\"OPT\":\"query\",\"type\":\"dao\"},\"body\":"
				+ "{\"poorFamilyList\":{\"conditions\":"
				+ "{\"query_AAR040\":\""+nd+"\",\"AAR002\":\"150000000000\","
						+ "\"AAR003\":\"150400000000\",\"AAR004\":\""+xian+"\","
						+ "\"AAR005\":\"\",\"AAR006\":null,\"AAR007\":null,\"aac006\":[],"
						+ "\"aac005\":\"\",\"aar010\":[],\"aab002\":\"\",\"aab004\":\"\","
						+ "\"show\":0,\"aar008\":\""+xian.substring(0, 6)+"\","
						+ "\"condition_diy\":[],\"aar040\":"+nd+"},\"namespace\":"
						+ "\"com.neusoft.biz.core.mapping.Ac01Mapper\",\"sqlId\":"
						+ "\"queryGrid\",\"page\":{\"pageSize\":"+pageSize+","
						+ "\"startRow\":"+startRow+"}},\"numberForm\":{\"conditions\":"
						+ "{\"query_AAR040\":\""+nd+"\",\"AAR002\":\"150000000000\","
						+ "\"AAR003\":\"150400000000\",\"AAR004\":\""+xian+"\",\"AAR005\":"
						+ "\"\",\"AAR006\":null,\"AAR007\":null,\"aac006\":[],\"aac005\":\"\","
						+ "\"aar010\":[],\"aab002\":\"\",\"aab004\":\"\",\"show\":0,\"aar008\":"
						+ "\""+xian.substring(0, 6)+"\",\"condition_diy\":[],\"aar040\":"+nd+"},"
						+ "\"namespace\":\"com.neusoft.biz.core.mapping.Ac01Mapper\",\"sqlId\":"
						+ "\"queryNumber\"}}}";
    	String t = System.currentTimeMillis()+"";
		String cData = "common/doQueryPOST"+t+xian.substring(0,9)+xian+condtion; 
		HMac hm = new HMac(HmacAlgorithm.HmacSHA256,xian.getBytes());  
		String jsonStr = this.execute(ImmutableMap.of("key1", t,"key2", hm.digestHex(cData),"key3", condtion), By.xpath("//*[@id=\"on_query\"]/span"));
		
		if("FAIL".equals(jsonStr)){
			return Response.fail();
		}else { 
			JsonParser jp=new JsonParser();  
			JsonObject jo=jp.parse(jsonStr).getAsJsonObject(); 
			int code = Integer.valueOf(jo.get("options").getAsJsonObject().get("code").toString());
			if(code == 1){
				JsonArray data = jo.get("body").getAsJsonObject().get("poorFamilyList").getAsJsonObject().get("data").getAsJsonArray();
				if(data == null || data.size() == 0){ 
					return Response.fail(RCode.dass900005, "没有当前查询信息");
		        } 
				Response response = Response.ok();
				response.body.size=pageSize+""; 
				JsonArray total = jo.get("body").getAsJsonObject().get("numberForm").getAsJsonObject().get("data").getAsJsonArray();
				response.body.totalCount=total.get(0).getAsJsonObject().get("HNUM").toString();
				response.body.sql = FPBTableUtils.pinkunhuxinxiliebiao(data,xian); 
				log.debug(response.body.sql);
				return response.toJson();
			}else{
				if(!jo.get("options").getAsJsonObject().get("errorMsg").isJsonNull()){
					String errorMsg=jo.get("options").getAsJsonObject().get("errorMsg").getAsString();
					if(errorMsg.contains("验证码过期")){ 
						return Response.fail(RCode.dass900001, "验证码错误");
					}else{ 
						return Response.fail(RCode.dass900006, errorMsg);
					}
				}else if(jo.get("options").getAsJsonObject().get("code").getAsInt()!=1){ 
					return Response.fail(RCode.dass900002, "用户名或密码错误");
				}else{
					return Response.fail();
				}
			} 
		} 
    }
    
    
    public String login2(String username,String password){
        try {
        	//登陆地址
        	driver.get("http://106.38.235.201:7080/portal/j_spring_security_check");  
            driver.findElement(By.id("j_username")).clear(); 
            driver.findElement(By.id("j_username")).sendKeys(username);
            driver.findElement(By.id("j_password")).clear(); 
            driver.findElement(By.id("j_password")).sendKeys(password);  
            driver.findElement(By.id("loginButton")).click();
             
            String currentHandle = driver.getWindowHandle();
            Set<String> handles = driver.getWindowHandles();    
            handles.forEach( h -> { 
                 if (h != currentHandle) {
                       //将窗口转换至点击登陆后的界面
                      driver.switchTo().window(h);
                      //输出跳转后页面的详细信息，打印到控制台，如果打印的HTML代码与正常登录后的界面代码相吻合，证明模拟登录成功 
                      driver.findElement(By.className("menuIcon1")).click();  
                      int t = new Random().nextInt(3) + 1;
                  	  driver.findElement(By.xpath("//*[@id='dialog']/div/center/div/div/ul/li["+t+"]/a")).click();  
                 } 
            }); 
            return factch(); 
		} catch (Exception e) {
			e.printStackTrace();
			return Response.fail(); 
		}
    }
    public String factch(){ 
         ((JavascriptExecutor) driver).executeScript("arguments[0].click();", driver.findElement(By.xpath("/html/body/app-root/div/div/app-main-layout/div/div[1]/div/div/app-menu/ul/nui-main-menu/div/div[6]/div[1]/a")));
         ((JavascriptExecutor) driver).executeScript("arguments[0].click();",  driver.findElement(By.xpath("/html/body/app-root/div/div/app-main-layout/div/div[1]/div/div/app-menu/ul/nui-main-menu/div/div[6]/div[2]/div/nui-main-menu-sub/ul/li/a")));
         ((JavascriptExecutor) driver).executeScript("arguments[0].click();", driver.findElement(By.xpath("/html/body/app-root/div/div/app-main-layout/div/div[1]/div/div/app-menu/ul/nui-main-menu/div/div[6]/div[2]/div/nui-main-menu-sub/ul/li/nui-main-menu-sub/ul/li[1]/a")));
         ((JavascriptExecutor) driver).executeScript("arguments[0].click();", driver.findElement(By.xpath("/html/body/app-root/div/div/app-main-layout/div/div[1]/div/div/app-menu/ul/nui-main-menu/div/div[6]/div[2]/div/nui-main-menu-sub/ul/li/nui-main-menu-sub/ul/li[1]/nui-main-menu-sub/ul/li[1]/a/span[2]")));
         String rse = this.execute(By.xpath("//*[@id=\"on_query\"]/span"));
         
         if("OK".equals(rse)){
        	 super.loginFlag = true;
        	 return Response.okJson();
         }else{
        	 super.loginFlag = false;
        	 return Response.fail(); 
         } 
    }
     
	
	public static void main(String[] args) throws InterruptedException, IOException{
		//FupinPageProcessor dpp = new FupinPageProcessor (); 
        //调用selenium，进行模拟登录
       // login1(); 
      //  Thread.sleep(3000);
       // factch(); 
    } 
}
